package patterns.design.e3t6;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class Cache implements ResourcesProvider {

	private ResourcesProvider downloader;
	
	public Cache(ResourcesProvider resourceDownloader)
	{
		this.downloader = resourceDownloader;
	}
	
	@Override
	public Resource provideResource(String url) throws Exception {
		Resource result = null;
		URL urlObject = null;
		urlObject = new URL(url);
		File contentFile = new File(urlObject.getPath().replace('/','_'));
		if(contentFile.exists())
		{
			result = new Resource(contentFile, url);
			System.out.println("File exist in cache, no need for downloading.");
		}
		else
		{
			result = downloader.provideResource(url);
		}
			
		return result;
	}

}
